//
//  AppDelegate.swift
//  SwiftWeibo
//
//  Created by Lucky on 16/4/19.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit

let SwitchRootViewControllerKey = "SwitchRootViewControllerKey"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.SwitchRootViewController(_:)), name: SwitchRootViewControllerKey, object: nil)
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
        //1，创建window
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        //2，创建根控制器
        
//        window?.rootViewController = MainViewController()
        window?.rootViewController = defaultController()
        window?.makeKeyAndVisible()
        
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func SwitchRootViewController(nofity: NSNotification) {
        
        if nofity.object as! Bool {
            window?.rootViewController = MainViewController()
        } else {
            window?.rootViewController = WelcomeViewController()
        }
        
    }
    
    private func defaultController() -> UIViewController {
        if UserAccount.userLogin() {
            return isNewupDate() ? NewFeatureCollectionViewController() : WelcomeViewController()
        }
        return MainViewController()
    }

    //判断是否是新版本
    private func isNewupDate() -> Bool {
        //获取当前的版本号
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        //获取以前的软件版本号，从本地文件读取
        let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
        //比较当前版本和以前版本的版本号
        if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending {
            //当前版本>以前版本
            //存储新版本号
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString") //iOS7之后不用调用同步方法
            return true
        }
        
        return false
    }
}

